package com.vista.questionnaire.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.vista.questionnaire.domain.Examination;

import com.vista.questionnaire.repository.ExaminationRepository;
import com.vista.questionnaire.service.AnswerPOIExport;
import com.vista.questionnaire.web.rest.errors.BadRequestAlertException;
import com.vista.questionnaire.web.rest.util.HeaderUtil;
import com.vista.questionnaire.web.rest.util.PraseTagUtils;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;

import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing Examination.
 */
@RestController
@RequestMapping("/api")
public class ExaminationResource {

    private final Logger log = LoggerFactory.getLogger(ExaminationResource.class);

    private static final String ENTITY_NAME = "examination";

    private final ExaminationRepository examinationRepository;

    private final PraseTagUtils praseTagUtils;

    private final AnswerPOIExport answerPOIExport;


    public ExaminationResource(ExaminationRepository examinationRepository, PraseTagUtils praseTagUtils, AnswerPOIExport answerPOIExport) {
        this.examinationRepository = examinationRepository;
        this.praseTagUtils = praseTagUtils;
        this.answerPOIExport = answerPOIExport;
    }

    @PostMapping("/examinations")
    @Timed
    public ResponseEntity<Examination> createExamination(@RequestBody Examination examination) throws URISyntaxException {
        examination.setQuestions(praseTagUtils.praseTags(examination.getContent()));
        log.debug("REST request to save Examination : {}", examination);
        if (examination.getId() != null) {
            throw new BadRequestAlertException("A new organization cannot already have an ID", ENTITY_NAME, "idexists");
        }
        Examination result = examinationRepository.save(examination);
        return ResponseEntity.created(new URI("/api/examinations/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    @PutMapping("/examinations")
    @Timed
    public ResponseEntity<Examination> updateExamination(@RequestBody Examination examination) throws URISyntaxException {
        examination.setQuestions(praseTagUtils.praseTags(examination.getContent()));
        log.debug("REST request to update Examination : {}", examination);
        if (examination.getId() == null) {
            return createExamination(examination);
        }
        Examination result = examinationRepository.save(examination);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, examination.getId().toString()))
            .body(result);
    }


    @RequestMapping(value = "/examinations/{id}/export", method = RequestMethod.GET)
    public void exportMiniProductReviewPDF(@PathVariable String id, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");//设置相应内容的编码格式
        response.setContentType("application/vnd.ms-excel");//定义输出类型
        response.setHeader("Content-Disposition", "attachment;filename=miniProductReview.xlsx");
        response.setHeader("Download-File-Name", new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".xlsx");
        this.answerPOIExport.export(response.getOutputStream(), this.examinationRepository.findOne(Long.valueOf(id)));
    }

    /**
     * GET  /examinations : get all the examinations.
     *
     * @return the ResponseEntity with status 200 (OK) and the list of examinations in body
     */
    @GetMapping("/examinations")
    @Timed
    public List<Examination> getAllExaminations() {
        log.debug("REST request to get all Examinations");
        return examinationRepository.findAll();
    }

    /**
     * GET  /examinations/:id : get the "id" examination.
     *
     * @param id the id of the examination to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the examination, or with status 404 (Not Found)
     */
    @GetMapping("/examinations/{id}")
    @Timed
    public ResponseEntity<Examination> getExamination(@PathVariable Long id) {
        log.debug("REST request to get Examination : {}", id);
        Examination examination = examinationRepository.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(examination));
    }

    /**
     * DELETE  /examinations/:id : delete the "id" examination.
     *
     * @param id the id of the examination to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/examinations/{id}")
    @Timed
    public ResponseEntity<Void> deleteExamination(@PathVariable Long id) {
        log.debug("REST request to delete Examination : {}", id);
        examinationRepository.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }


}
